// app.js
require('./utils/index.js');
require('./config.js');
(function(G) {
  ///为所有post方法添加unitId
  G.Storage.set('beforeLoginAction',function(){
    let unitId = G.Storage.get('unitId');
    if(this.type.toUpperCase() == 'POST' && unitId != 'hw' && !this.data.unitId){
      this.data.unitId = unitId
    }
  })
  G.addClock = function(args){
    args = args || {}
    let { longitude,latitude,address } = args
    let time1 = new Date(args.time)
    let clockParam = {},userInfo = G.Storage.get('userInfo')
    clockParam.clockType = 1
    clockParam.userId = userInfo.userId
    clockParam.userName = userInfo.name
    clockParam.vxUserid = userInfo.userName
    clockParam.checkinTime = parseInt(time1.getTime() / 1000) || parseInt(new Date().getTime() / 1000)
    clockParam.locationDetail = address
    clockParam.lat = parseFloat(latitude) * 1000000
    clockParam.lng = parseFloat(longitude) * 1000000
    console.log('--clockParam', clockParam)
    return G.post('/api/model/clock', clockParam)
  }  
  G.postWeRun = function(){//上报微信步数
    return new Promise(next => {
        wx.getWeRunData({
            success (res) {
                G.post('/v1/weRunData',res).then(res => {
                    next({})
                })
            },
            fail(err){
                // next({})
                // next({ errorMsg:'获取运动步数失败' })
                G.alert('请授权开启微信运动步数',{
                    title:'微信运动提示'
                }).then(res => {
                    next({ errorMsg:'获取运动步数失败' })
                    wx.openSetting()
                })
                // G.postWeRun()
            }
        })
    })
}
  let loginTimes = 0
  G.App({
    onError: function(error) {
      //G.reEnter('/pages/err/err?msg=系统错误,请退出微信重试!\r\n' + error);
    },
    //onLogin: '/pages/auth/auth',
    onLaunch:function(options){
        wx.getSetting({
            success(res){
                console.log(res)
            }
        })
        let takePicMode = G.Storage.get('takePicMode',1)
        if(takePicMode) wx.reLaunch({
          url: '/pages/takepic/takepic/index',
        })
    },
    autoLogin: function(success, fail) {
      if(loginTimes > 2){
        G.$go('/pages/err/err')
      }else{
        loginTimes ++
      }
      wx.login({
        success: function (ret) {
          console.log('1111111');
          if (ret.code) {
            G.get('/WeChatMiniAppLogin',{
              code:ret.code,
              unitId:G.Storage.get('unitId')
            }, function (ret) {
              if (!ret.errorMsg) {
                  ret.id = ret.userId
                G.Storage.set('userInfo', ret);
                G.Storage.set('unitId',ret.unitId);
                G.Storage.set('ajaxHeader', [{
                  key: 'token',
                  value: ret.token
                },{
                  key: 'unitId',
                  value: 'hw'
                }], {
                  type: 2
                })
                success();
              } else {
                fail(ret.errorMsg, 'codeLoginError');
              }
            })
          } else {
            fail(ret, 'wxNoCode');
          }
        },
        fail: function (ret) {
          fail(ret, 'wxLoginError');
        }
      })
    },
    Interceptor: function(data, next) {
        var _this = this,userInfo = G.Storage.get('userInfo');
      switch (data.code) {
        case 400:
          G.Storage.remove('user', 1);
          G.Storage.get('autoLogin')(function() {
            _this.action();
          })
          break;
        case 1000:
          next(data.data || data);
          break;
        default:
          if (data.msg || data.errMsg) data.errorMsg = data.msg || data.errMsg;
          //数据操作记录
          if(!data.errorMsg && /(post)|(put)|(delete)/i.test(this.type) && userInfo){
            let modelName = this.url.split('/api/model/')[1]
            if(modelName && modelName != 'user_action_record')
            G.post('/api/model/user_action_record',{
              userId:userInfo.userId,//操作人ID
              userName:userInfo.name,//操作人名字
              type:this.type.toUpperCase(),
              model:modelName,//表名
              tableId:data.id || this.data.id,//操作ID
              data:JSON.stringify(this.data),//请求数据
              result:JSON.stringify(data)//请求结果
            },null,{errNotify:false})
          }
          next(data);
          break;
      }
    }
  })
})(wx.$)